import UPNG from "./UPNG.js";
import {
  fileToDataURL,
  dataURLToImage,
  convertQualityToBit,
} from "./image";

export async function shrinkImage(file, quality) {
  if (!file) throw new Error("file can not be null");
  if (!file.type.includes("image/")) throw new Error("file must be image");
  try {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    const base64 = await fileToDataURL(file);
    // console.log(base64);
    const img = await dataURLToImage(base64);
    // console.log(img);
    canvas.width = img.width;
    canvas.height = img.height;
    context.clearRect(0, 0, img.width, img.height);
    context.drawImage(img, 0, 0, img.width, img.height);
      const imageData = context.getImageData(
        0,
        0,
        img.width,
        img.height
      ).data;
      const bit = convertQualityToBit(quality);

      const png = UPNG.encode([imageData.buffer], img.width, img.height, bit);
      return new File([png], file.name, {
        type: file.type,
      });
    
  } catch (error) {
    throw new Error(error.message);
  }
}